<template>
  <el-dialog v-model="visible" :title="title" width="520" show-footer show-zoom resize :close-on-click-modal="false"
    :close-on-press-escape="false" @close="close">
    <template #default>
      <el-form ref="formRef" :rules="rules" :model="form" label-align="right" label-width="120" size="default"
        label-position="top">
        <el-form-item label="SKU" prop="floor_name">
          <el-input v-model="form.sku" placeholder="请输入" disabled></el-input>
        </el-form-item>
        <el-form-item label="赛盒编号" prop="irobot_box_code">
          <el-input v-model="form.irobot_box_code" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="status" disabled>
          <el-input type="textarea" v-model="form.sku_cn_title" placeholder="请输入" disabled></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="flex justify-center py-2">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save(formRef)">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { getIrobotBoxDetail, updateIrobotBox } from '../api/index'
import { reactive, ref, toRefs } from 'vue'
import { ElMessage } from 'element-plus'

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(['query'])

const data = reactive({
  form: {},
  title: '新增',
  handleType: null,
  rules: {
    irobot_box_code: [{
      required: true, message: '请输入赛盒编号', trigger: 'blur'
    }],
  },
})
const { form, title, handleType, rules } = toRefs(data)

const statusMap = new Map([
  ['add', '新增'],
  ['edit', '编辑'],
  ['view', '查看'],
])

const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  form.value = getForm()
}
// 初始化
const getForm = () => {
  return {}
}

onMounted(() => {
  initForm()
})


const getDetail = async (id) => {
  try {
    const res = await getIrobotBoxDetail({
      id
    })
    form.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

const save = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      if (form.value.id) {
        updateIrobotBox({
          id: form.value.id,
          irobot_box_code: form.value.irobot_box_code
        })
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      }
    }
  })
}
const close = () => {
  initForm()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.borderNone {
  :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none
  }
}
</style>
